<template>
<div class="layout">
	<Row>
		<Col :span="24">
			<Breadcrumb>
				<BreadcrumbItem to="/" @click.native="changeMenu(0)"><Icon type="home"></Icon> 首页</BreadcrumbItem>
				<BreadcrumbItem :to="{'name':'timecoin-publisher-index'}" @click.native="changeMenu('timecoin_publisher_index')">发行人列表</BreadcrumbItem>
				<BreadcrumbItem>{{title}}</BreadcrumbItem>
			</Breadcrumb>
			<div class="cleaner20"></div>
		</Col>
		<Col :span="24">
			<Steps :current="stepIndex">
				<Step title="基本信息"></Step>
				<Step title="内容简介"></Step>
				<Step title="完成"></Step>
			</Steps>
			<div class="cleaner20"></div>
		</Col>
	</Row>
	<Tabs :value="tabIndex">
        <TabPane label="基本信息" name="tab1" >
			<Form ref="vform" :model="vform" :label-width="80" :rules="ruleValidate">
				<Row>
					<Col :span=24>
						<FormItem label=" ">
							<Avatar :src="vform.avatar"  style="width:80px;height:80px" />
							<input v-model="vform.avatar" type="hidden"></input>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem label="代码" prop="code">
							<Input  v-model="vform.code" placeholder="请填写代码"></Input>
						</FormItem>
						<FormItem label="姓名" prop="name">
							<Input v-model="vform.name" placeholder="请填写姓名"></Input>
						</FormItem>
						<FormItem label="状态" prop="status">
							<Select placeholder="请选择状态" v-model="vform.status" style="">
								<Option v-for="item in statusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
							</Select>
						</FormItem>
						<FormItem label="分类" prop="classify">
							<Select placeholder="请选择分类" v-model="vform.classify" style="" @on-change="changeClassify" :label-in-value="true">
								<Option  v-for="item in classifyList" :value="item.value" :key="item.value" >{{ item.label }}</Option>
							</Select>
						</FormItem>
						<FormItem label="权重" prop="sequence">
							<InputNumber :max="9999" :min="1" v-model="vform.sequence"></InputNumber>
						</FormItem>
						<FormItem label="认证" >
							<Select v-model="vform.authentication" multiple  placeholder="请选择认证">
								<Option v-for="item in authencationList" :value="item.value" :key="item.value">{{ item.label }}</Option>
							</Select>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem label="出生年月" prop="born_at">
							<DatePicker @on-change="changeDate" :value="vform.born_at" type="date" show-week-numbers placement="bottom-end" placeholder="请选择出生年月"></DatePicker>
							
						</FormItem>
						<FormItem label="国籍" prop="nation">
							<Input v-model="vform.nation" placeholder="请填写国籍"></Input>
						</FormItem>
						<FormItem label="名族" prop="ethnic_group">
							<Input v-model="vform.ethnic_group" placeholder="请填写名族"></Input>
						</FormItem>
						<FormItem label="身价" prop="value">
							<InputNumber :max="9999999" :min="10" :step="0.01" v-model="vform.value"></InputNumber><span>（万元）</span>
						</FormItem>
						<FormItem label="职业" prop="occupation">
							<Input v-model="vform.occupation" placeholder="请填写职业"></Input>
						</FormItem>
						<FormItem label="毕业院校" prop="colleage">
							<Input v-model="vform.colleage" placeholder="请填写毕业院校"></Input>
						</FormItem>
					</Col>
					<Col span="24">
						<FormItem label=" ">
							<Button @click="save" type="primary">保存基本信息</Button>
						</FormItem>
					</Col>

				</Row>
			</Form>

		</TabPane>
        <TabPane label="内容简介" name="tab2" v-if="showEditor">

			<Form ref="vSummaryForm"  :label-width="100" >
				<Row>
					<Col :span=24>
						<FormItem label="图片列表">
							<div  v-for="(item,index) in vSummaryForm.images" :key="index" class="camera-wrapper">
								<img :src="item" />
								<div class="list-cover">
									<Icon type="ios-eye-outline" @click.native="onView(item)"></Icon>
									<Icon type="ios-trash-outline" @click.native="onRemove(index)"></Icon>
								</div>
							</div>
							<Button v-if="vSummaryForm.images.length<5" class="btn-camera" type="text" @click="getPictures(4)">
								<Icon type="ios-camera" size="20"></Icon>
							</Button>
						</FormItem>
					</Col>
					<Col :span=24>
						<FormItem label="主要经历">
							<quill-editor ref="quill1" v-model="vSummaryForm.experience" :options="editorOption"></quill-editor>
						</FormItem>
					</Col>
					<Col :span=24>
						<FormItem label="时间使用范围">
							<quill-editor ref="quill2" v-model="vSummaryForm.timerange" :options="editorOption2"></quill-editor>
						</FormItem>
					</Col>
					<Col :span=24>
						<FormItem label="主要成就">
							<quill-editor ref="quill3" v-model="vSummaryForm.achievement" :options="editorOption3"></quill-editor>
						</FormItem>
					</Col>
					<Col span="24">
						<FormItem label=" ">
							<Button @click="summarySave" type="primary">保存内容简介</Button>
						</FormItem>
						
					</Col>
				</Row>
			</Form>

		</TabPane>
    </Tabs>

	<Button type="text" @click="getPictures(1)" id="btnShowPictureBox"></Button>
	<Button type="text" @click="getPictures(2)" id="btnShowPictureBox2"></Button>
	<Button type="text" @click="getPictures(3)" id="btnShowPictureBox3"></Button>
	<Picture-Selector :show.sync="showPictureBox" @on-hide="showPictureBox=false" @on-change="insertImage"></Picture-Selector>
	
    <Modal title="查看图片" v-model="currentImagvisible">
        <img :src="currentImag" v-if="currentImagvisible" style="width: 100%">
    </Modal>

</div>
</template>
<script>
// 引入子组件
import hljs from 'highlight.js'
hljs.configure({   // optionally configure hljs
  languages: ['javascript', 'ruby', 'python','xml']
});

import PictureSelector from '@/components/PictureSelector/PictureSelector.vue'
//quill编辑器的字体
var fonts = ['SimSun', 'Microsoft-YaHei','Arial','Times-New-Roman','sans-serif'];  
var Font = Quill.import('formats/font');  
Font.whitelist = fonts; //将字体加入到白名单 
Quill.register(Font, true);


import {mapState,mapGetters} from 'vuex'
import {Steps, Step,  Tabs, TabPane, Spin, Row, Col,  Button,  Breadcrumb, BreadcrumbItem, Icon, Form, FormItem, Input, Avatar, Select, Option, DatePicker, InputNumber } from 'iview';
export default { 
	name:'publisher-view',
	components: {  PictureSelector,Steps, Step,  Tabs, TabPane, Spin, Row, Col, Button, Breadcrumb, BreadcrumbItem, Icon, Form, FormItem, Input, Avatar, Select, Option, DatePicker, InputNumber},
	data () {
		return {
			stepIndex:0,
			tabIndex:'tab1',
			showPictureBox:false,
			spinShow:true,
			currentImag:'',
			currentImagvisible:false,
			editorIndex:1,
			showEditor:false,
			editorOption:{
				placeholder:'请输入内容',
				modules:{
					imageResize: {},
					toolbar:{
                        container: [
							['bold', 'italic', 'underline', 'strike'],        // toggled buttons
							['blockquote', 'code-block'],           // custom button values
							[{ 'list': 'ordered'}, { 'list': 'bullet' }],
							[{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
							[{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
							['link'],
							[{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
							[{ 'header': [1, 2, 3, 4, 5, 6, false] }],

							[{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
							[{ 'font': fonts }],
							[{ 'align': [] }],
							['clean'],
                            ['vimage'],   
                        ],
                        handlers: {'vimage': function() {document.getElementById("btnShowPictureBox").click()}}
                    },
					syntax: {highlight: text => hljs.highlightAuto(text).value},


				}
			},
			editorOption2:{
				placeholder:'请输入内容',
				modules:{
					imageResize: {},
					toolbar:{
						container: [
							['bold', 'italic', 'underline', 'strike'],        // toggled buttons
							['blockquote', 'code-block'],          // custom button values
							[{ 'list': 'ordered'}, { 'list': 'bullet' }],
							[{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
							[{ 'indent': '-1'}, { 'indent': '+1' }],
							['link'],
							[{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
							[{ 'header': [1, 2, 3, 4, 5, 6, false] }],

							[{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
							[{ 'font': fonts }],
							[{ 'align': [] }],
							['clean'],
                            ['vimage'],   
                        ],
                        handlers: {'vimage': function() {document.getElementById("btnShowPictureBox2").click()}}
                    },
					syntax: {highlight: text => hljs.highlightAuto(text).value}
				}
			},
			editorOption3:{
				placeholder:'请输入内容',
				modules:{
					imageResize: {},
					toolbar: {
                        container: [
							['bold', 'italic', 'underline', 'strike'],        // toggled buttons
							['blockquote', 'code-block'],           // custom button values
							[{ 'list': 'ordered'}, { 'list': 'bullet' }],
							[{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
							[{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
							['link'],
							[{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
							[{ 'header': [1, 2, 3, 4, 5, 6, false] }],

							[{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
							[{ 'font': fonts }],
							[{ 'align': [] }],
							['clean'],
                            ['vimage'],   
                        ],
                        handlers: {'vimage': function() {document.getElementById("btnShowPictureBox3").click()}}
                    },
					syntax: {highlight: text => hljs.highlightAuto(text).value}
				}
			},
			title:'新增',
			vform:{
				status:"0",
				sequence:0,
				name:"",
				code:"",
				classify:"",
				classify_name:"",
				avatar:"/static/images/avatar.png",
				value:0,
				ethnic_group:"",
				nation:"",
				born_at: '',
				occupation:"",
				colleage:"",
				authentication:[]
			},
			vSummaryForm:{
				id:1,
				code:'800019',
				experience:'<p>678</p>',
				timerange:'',
				achievement:'',
				images:''
			},
			ruleValidate: {
				name: [
					{ required: true, message: '请填写姓名', trigger: 'blur' }
				],
				code: [
					{ required: true, message: '请填写代码', trigger: 'blur' }
				],
				status: [
					{ required: true, message: '请选择状态', trigger: 'change' }
				],
				sequence: [
					{ required: true, type:'number', message: '请填写权重', trigger: 'change' }
				],
				classify: [
					{ required: true, message: '请选择分类', trigger: 'change' }
				],
				classify_name: [
					{ required: true, message: '请填写分类', trigger: 'blur' }
				],
				value: [
					{ required: true, type:'number', message: '请填写身价', trigger: 'change' }
				],
				ethnic_group: [
					{ required: true, message: '请填写民族', trigger: 'blur' }
				],
				nation: [
					{ required: true, message: '请填写国籍', trigger: 'blur' }
				],
				born_at:  [
					{ required: true, message: '请选择出身年月', trigger: 'change' }
				],
				occupation: [
					{ required: true, message: '请填写职业', trigger: 'blur' }
				],
				colleage: [
					{ required: true, message: '请填写毕业院校', trigger: 'blur' }
				],
			},
			statusList: [
				{value: "0",label: '暂存'},
				{value: "1",label: '上架'},
				{value: "2",label: '下架'},
				{value: "3",label: '屏蔽'}
			],
			
			classifyList: [
				{value: "0",label: '创业者'},
				{value: "1",label: '企业家'},
				{value: "2",label: '艺人'},
				{value: "3",label: '牛人'},
				{value: "4",label: '校咖'},
				{value: "5",label: '公益'}
			],
			authencationList:[
				{value: "名人认证",label: '名人认证'},
				{value: "VIP认证",label: 'VIP认证'},
			]

		}
	},
	methods:{
		init:function(){
		},
		changeClassify:function(obj){
			this.vform.classify_name=obj.label
		},
		changeMenu:function(nid){
			let _index = 0
			this.menuIndex.forEach(item=>{
				if(nid==item.nid){
					_index=item.id
				}
			})
			this.$store.dispatch('setMenuActive',_index+'')
			this.$store.dispatch('setMenuOpen', [_index+''])
			return false;
		},
		changeDate:function(val, obj){
			this.vform.born_at=val
		},
		submit:function(){
			let self=this
			self.$store.dispatch("setSpinShow",true)
			self.$http.post("/v1/publishers?token="+self.token,{'data':JSON.stringify(self.vform)})
			.then(function(response){
				if(200==response.data.status && 0==response.data.code)
				{
					self.vSummaryForm.id=response.data.data.id
					self.vSummaryForm.code=self.vform.code
					self.showEditor=true
					self.vform.code=''
					self.tabIndex='tab2'
					self.stepIndex=1
					self.$Notice.success({title: '操作成功',desc:''});
				}else{
					
					self.$Notice.error({desc: response.data.message,title:'错误'});
				}
				self.$store.dispatch("setSpinShow",false)
			}).catch(function(error){
				self.$Notice.error({desc: error.message,title:'错误'});
				self.$store.dispatch("setSpinShow",false)
			})
		},
		save:function(){
			let self=this
			this.$refs['vform'].validate((valid) => {
				if (!valid) {
					this.$Notice.error({title:'错误',desc:'字段没有按要求填写，请检查!'});
				}else{
					this.submit()
				}
			})

		},
		summarySave:function(){
			let self=this
			self.$store.dispatch("setSpinShow",true)
			self.$http.post("/v1/summaries?token="+self.token,{'data':JSON.stringify(self.vSummaryForm)})
			.then(function(response){
				if(200==response.data.status && 0==response.data.code)
				{
					self.vform.code=''
					self.$Notice.success({title: '操作成功',desc:''});
				}else{
					
					self.$Notice.error({desc: response.data.message,title:'错误'});
				}
				self.$store.dispatch("setSpinShow",false)
			}).catch(function(error){
				self.$Notice.error({desc: error.message,title:'错误'});
				self.$store.dispatch("setSpinShow",false)
			})
		},
		getPictures:function(index){
			let self=this
			self.editorIndex=index
			self.showPictureBox=true
		},
		insertImage:function(url){
			if(4==this.editorIndex){
				this.vSummaryForm.images=''==this.vSummaryForm.images?[]:this.vSummaryForm.images
				if(this.vSummaryForm.images.length<5)this.vSummaryForm.images.push(url)
				
			}else{
				// 获取富文本组件实例
				let quill = this.$refs.quill1.quill
				if(2==this.editorIndex){quill = this.$refs.quill2.quill}
				if(3==this.editorIndex){quill = this.$refs.quill3.quill}
				// 获取光标所在位置
				let length = quill.getSelection().index;
				// 插入图片  res.info为服务器返回的图片地址
				quill.insertEmbed(length, 'image', url)
				// 调整光标到最后
				quill.setSelection(length + 1)
			}
			this.showPictureBox=false

		},
		onRemove:function(index){this.vSummaryForm.images.splice(index,1)},
		onView:function(url){
			this.currentImag=url
			this.currentImagvisible=true
		}
	},
	created:function(){
	},
	mounted () {
		this.init()
    	this.setTitle(this.title)
	},
	activated:function(){
		this.init()
	},
	computed:{
		...mapGetters(['token','menuIndex']),
		contentCode() {
			return hljs.highlightAuto(this.vSummaryForm.experience).value
		},
	}
}



</script>
<style lang="less" scoped>
.fieldset-wrapper{
	padding:15px;
	legend{
		padding: 5px 10px;
		font-size: 14px;
		box-shadow: 1px 1px 7px 2px rgba(0,0,0,0.2);
	}
}


.camera-wrapper{
	display: inline-block;
	width: 60px;
	height: 60px;
	text-align: center;
	line-height: 60px;
	border: 1px solid transparent;
	border-radius: 4px;
	overflow: hidden;
	background: #fff;
	position: relative;
	box-shadow: 0 1px 1px rgba(0,0,0,.2);
	margin-right: 4px;
    
	img{width: 100%;height: 100%;}
	.list-cover{
		display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
		background: rgba(0,0,0,.6);
		i{
			color: #fff;
			font-size: 20px;
			cursor: pointer;
			margin: 0 2px;
		}
	}
}
.camera-wrapper:hover .list-cover{display: block;}

.btn-camera{border:1px dashed #dcdee2;width:58px;height:58px;vertical-align: text-bottom;}
.btn-camera:hover{border:1px dashed #5cadff;}
</style>